package org.idea.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.idea.netty.config.HttpServerInitializer;

import java.awt.*;
import java.net.InetSocketAddress;

/**
 * 基于netty编写的一个http服务器
 *
 * @Author idea
 * @Date created in 9:56 下午 2020/5/2
 */
public class NettyHttpServer {

    private int port;

    public NettyHttpServer(int port){
        this.port = port;
    }

    public void start() throws Exception{
        ServerBootstrap bootstrap = new ServerBootstrap();
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup work = new NioEventLoopGroup();
        bootstrap.group(boss,work)
                .handler(new LoggingHandler(LogLevel.DEBUG))
                .channel(NioServerSocketChannel.class)
                .childHandler(new HttpServerInitializer());

        ChannelFuture f = bootstrap.bind(new InetSocketAddress(port)).sync();
        System.out.println(" server start up on port : " + port);
        f.channel().closeFuture().sync();

    }


    public static void main(String[] args) throws Exception {
        NettyHttpServer server = new NettyHttpServer(8081);// 8081为启动端口
        server.start();
    }
}
